package com.example.backend.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {


    @Bean
    @ConditionalOnMissingBean(CacheManager.class)
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();

        // 用户缓存 - 写入后30分钟过期，最大1000条
        cacheManager.registerCustomCache("users", Caffeine.newBuilder()
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .maximumSize(1000)
                .build());

        // 通用缓存配置 - 1小时访问过期，最大500条
        Caffeine<Object, Object> commonCacheBuilder = Caffeine.newBuilder()
                .expireAfterAccess(1, TimeUnit.HOURS)
                .maximumSize(1000);

        // 产品缓存
        cacheManager.registerCustomCache("products", commonCacheBuilder.build());

        // 订单商品缓存
        cacheManager.registerCustomCache("orderGoods", commonCacheBuilder.build());

        // 角色名称缓存
        cacheManager.registerCustomCache("roleName", commonCacheBuilder.build());

        return cacheManager;
    }

}
